const router = require('express').Router();
const WxUtil = require('../../service/pay/wxPay');
const joi = require('joi');
const joiValidate = require('../../utils/joiValidate');
const verifyUser = require('../../utils/jwtHanlder');
const withDrawService = require('../../service/pay/withDraw');
const LockUtil = require('../../utils/lockUtil');
const ErrorCode = require('../../utils/errorCode');
/**
 * @apiDefine Wxpay  微信支付
 */

router.post('/notify', (req, res, next) => {
  const { xml } = req.body;
  const map = {};
  for (const i in xml) {
    if (xml.hasOwnProperty(i)) {
      map[i] = xml[i][0];
    }
  }
  new WxUtil().notify(map)
    .then(() => res.json({ return_code: 'SUCCESS', return_msg: 'OK' }))
    .catch(e => res.json(e));
});

/**
 * @api {post} /wxpay/pay  微信支付
 * @apiVersion 1.0.0
 * @apiName wxPay
 * @apiGroup  Wxpay
 *
 * @apiDescription 微信支付
 *
 * @apiParam {Number} orderId  订单Id
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/wxpay/pay
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 * @apiSuccess {Object} data    数据集合
 * @apiSuccess {Object} data.payInfo    数据集合
 * @apiSuccess {String} data.payInfo.prepayId    数据相关
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 {
    "code": 200,
    "message": "请求成功",
    "data": {
        "payInfo": {
            "prepayId": "prepay_id=wx191952532287923d0fffda3f1579010000",
            "sign": "0C4A21EB4657DF8FA456E1CDDD034361",
            "nonceStr": "p6dEhHRiVHU2WYyP",
            "appid": "wx814d8e19f0064f25",
            "mchid": "1517474111",
            "timestamp": "1560945172"
        }
    }
}
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */

router.post('/pay', verifyUser.verify(), joiValidate(joi.object().keys({
  orderId: joi.number().required().label('请输入订单Id')
})), (req, res, next) => {
  const { orderId } = req.body;
  const { userId, openid } = req.user;
  const { ip } = req;
  new WxUtil().buy({ orderId, userId, openid, ip })
    .then((data) => res.success({ payInfo: data }))
    .catch(e => next(e))
});

/**
 * @api {post} /wxpay/withdraw/apply  微信提现申请
 * @apiVersion 1.0.0
 * @apiName wxPayWithDrawApply
 * @apiGroup  Wxpay
 *
 * @apiDescription 微信提现申请
 *
 * @apiParam {Number} amount  金额
 *
 * @apiExample Example usage:
 * curl -i http://localhost:3502/wxpay/withdraw/apply
 *
 * @apiSuccess {Number} code      请求结果编码，0：正常， 其他为异常
 * @apiSuccess {string} message    请求结果编码对应的message
 *
 * @apiSuccessExample 正常响应：
 *     HTTP/1.1 200
 {
    "code": 200,
    "message": "请求成功"
}
 *
 *
 * @apiError  ServerError  服务器异常
 *
 * @apiErrorExample Response (example):
 *     HTTP/1.1 500 ServerError
 *     {
 *       "code": 500,
 *       "message": "服务器异常"
 *     }
 */
router.post('/withdraw/apply',  verifyUser.verify(), joiValidate(joi.object().keys({
  amount: joi.number().required().label('请输入要提现的金额')
})), (req, res, next) => {
  const { amount } = req.body;
  const { userId } = req.user;
  const lockUtil = new LockUtil(`user:withdraw:${userId}:`, 120); // 用户提现
  return lockUtil.tryLock()
    .then(() => withDrawService.createApply({ userId, amount }))
    .then(() => {
      // 删除请求锁
      lockUtil.unlock().catch(console.error);
      res.success();
    })
    .catch((err) => {
      // 非频繁访问时删除频繁队列key
      if (err.code !== ErrorCode.FREQUENT_REQUEST) lockUtil.unlock().catch(console.error);
      next(err);
    });
});

module.exports = router;
